package com.supinfo.sun.sungamers.dao.impl;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.supinfo.sun.sungamers.dao.PersonDAO;
import com.supinfo.sun.sungamers.person.Person;

/**
 * @author Liu, Bing(Locke)
 * @since 2011-04-05
 * @version 0.3
 */
public class PersonFile implements PersonDAO {

	public void savePersons(List<Person> persons) {
		try {
			FileOutputStream fos = new FileOutputStream("./person.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			// oos.writeInt(persons.size());

			Iterator<Person> it = persons.iterator();
			while (it.hasNext()) {
				Person person = it.next();
				oos.writeObject(person);
			}
			oos.flush();
			fos.flush();
			oos.close();
			fos.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException e) {
			System.out.println("exception happened during the IO process");
		}
	}

	public List<Person> getPersons() {
		List<Person> persons = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream("./person.ser");
			ois = new ObjectInputStream(fis);

			persons = new ArrayList<Person>();
			Person person;
			while ((person = (Person) ois.readObject()) != null) {
				if (person instanceof Person) {
					persons.add(person);
				}
			}
			ois.close();
			fis.close();
		} catch (EOFException e) {
			System.out.println("End of File");
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException e) {
			System.out.println("exception happened during the IO process");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Class not found");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (ois != null) {
					ois.close();
				}
			} catch (IOException e) {
				System.out.println("exception happened when closing ObjectInputStream");
			}
		}
		return persons;
	}

	public void appendPerson(Person p) {
		// TODO Auto-generated method stub

	}

	public Person getPerson(int id) {
		List<Person> list = getPersons();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Person p = (Person) it.next();
			if (p.getId() == id) {
				return p;
			}
		}
		return null;
	}

	public void updatePerson(Person p) {
		// TODO Auto-generated method stub

	}

	public void deletePerson(Person p) {
		// TODO Auto-generated method stub

	}
}
